import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, Input, Select, message, Popconfirm, Upload, DatePicker } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';
import SearchForm from './SearchForm';
import AuthorizedButton from '@/components/Authorized/AuthorizedButton';

// 获取加盟商列表
const fetchFranchises = async (params) => {
  return request('/api/v1/franchise', {
    method: 'GET',
    params,
  });
};

// 创建加盟商
const createFranchise = async (data) => {
  return request('/api/v1/franchise', {
    method: 'POST',
    data,
  });
};

// 更新加盟商
const updateFranchise = async (data) => {
  const { id, ...rest } = data;
  return request(`/api/v1/franchise/${id}`, {
    method: 'PUT',
    data: rest,
  });
};

// 删除加盟商
const deleteFranchise = async (id) => {
  return request(`/api/v1/franchise/${id}`, {
    method: 'DELETE',
  });
};

const FranchiseList = () => {
  const [franchises, setFranchises] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加加盟商');
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  
  // 搜索参数
  const [searchParams, setSearchParams] = useState({});

  // 获取加盟商列表
  const fetchFranchiseList = async () => {
    try {
      setLoading(true);
      const res = await fetchFranchises({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setFranchises(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取加盟商列表失败');
      }
    } catch (error) {
      console.error('获取加盟商列表出错:', error);
      message.error('获取加盟商列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchFranchiseList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '加盟商名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'Logo',
      dataIndex: 'logo',
      key: 'logo',
      render: (logo) => logo ? <img src={logo} alt="Logo" style={{ width: 50, height: 50 }} /> : '-',
    },
    {
      title: '联系人',
      dataIndex: 'contact',
      key: 'contact',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span style={{ color: status === 1 ? 'green' : 'red' }}>
          {status === 1 ? '正常' : '禁用'}
        </span>
      ),
    },
    {
      title: '合约到期时间',
      dataIndex: 'expire_at',
      key: 'expire_at',
      render: (expire_at) => expire_at ? moment(expire_at * 1000).format('YYYY-MM-DD') : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (created_at) => moment(created_at * 1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <AuthorizedButton
            permission="franchise:update"
            type="primary"
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </AuthorizedButton>
          <Popconfirm
            title="确定要删除该加盟商吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <AuthorizedButton permission="franchise:delete" type="danger" icon={<DeleteOutlined />} size="small">
              删除
            </AuthorizedButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setPagination({
      ...pagination,
    });
  };
  
  // 处理搜索
  const handleSearch = (values) => {
    setSearchParams(values);
    setPagination({
      ...pagination,
      current: 1, // 搜索时重置为第一页
    });
  };
  
  // 处理重置搜索
  const handleResetSearch = () => {
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1, // 重置搜索时重置为第一页
    });
  };

  // 处理添加按钮点击
  const handleAdd = () => {
    setModalTitle('添加加盟商');
    setEditingId(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 处理编辑按钮点击
  const handleEdit = (record) => {
    setModalTitle('编辑加盟商');
    setEditingId(record.id);
    form.setFieldsValue({
      ...record,
      expire_at: record.expire_at ? moment(record.expire_at * 1000) : null,
    });
    setModalVisible(true);
  };

  // 处理删除按钮点击
  const handleDelete = async (id) => {
    try {
      const res = await deleteFranchise(id);
      if (res.success) {
        message.success('删除加盟商成功');
        fetchFranchiseList();
      } else {
        message.error(res.message || '删除加盟商失败');
      }
    } catch (error) {
      console.error('删除加盟商出错:', error);
      message.error('删除加盟商失败');
    }
  };

  // 处理模态框确认
  const handleModalOk = () => {
    form.validateFields().then(async (values) => {
      // 转换日期为时间戳
      if (values.expire_at) {
        values.expire_at = values.expire_at.unix();
      }

      try {
        let res;
        if (editingId) {
          // 更新
          res = await updateFranchise({
            id: editingId,
            ...values,
          });
        } else {
          // 创建
          res = await createFranchise(values);
        }

        if (res.success) {
          message.success(editingId ? '更新加盟商成功' : '创建加盟商成功');
          setModalVisible(false);
          fetchFranchiseList();
        } else {
          message.error(res.message || (editingId ? '更新加盟商失败' : '创建加盟商失败'));
        }
      } catch (error) {
        console.error(editingId ? '更新加盟商出错:' : '创建加盟商出错:', error);
        message.error(editingId ? '更新加盟商失败' : '创建加盟商失败');
      }
    });
  };

  // 处理模态框取消
  const handleModalCancel = () => {
    setModalVisible(false);
  };

  return (
    <PageContainer>
      <Card
        title="加盟商管理"
        extra={
          <AuthorizedButton permission="franchise:create" type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加加盟商
          </AuthorizedButton>
        }
      >
        <SearchForm onSearch={handleSearch} onReset={handleResetSearch} />
        <Table
          columns={columns}
          dataSource={franchises}
          rowKey="id"
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />
      </Card>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={700}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            status: 1,
          }}
        >
          <Form.Item
            name="name"
            label="加盟商名称"
            rules={[{ required: true, message: '请输入加盟商名称' }]}
          >
            <Input placeholder="请输入加盟商名称" />
          </Form.Item>

          <Form.Item name="logo" label="Logo">
            <Input placeholder="请输入Logo URL" />
          </Form.Item>

          <Form.Item name="description" label="描述">
            <Input.TextArea rows={4} placeholder="请输入加盟商描述" />
          </Form.Item>

          <Form.Item
            name="contact"
            label="联系人"
            rules={[{ required: true, message: '请输入联系人' }]}
          >
            <Input placeholder="请输入联系人" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="联系电话"
            rules={[{ required: true, message: '请输入联系电话' }]}
          >
            <Input placeholder="请输入联系电话" />
          </Form.Item>

          <Form.Item name="email" label="邮箱">
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item name="address" label="地址">
            <Input placeholder="请输入地址" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Select.Option value={1}>正常</Select.Option>
              <Select.Option value={0}>禁用</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="expire_at" label="合约到期时间">
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default FranchiseList;